package com.jing.weibo.controller.fansattention;

import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import weibo4j.model.WeiboException;

import com.jing.system.comm.BaseController;
import com.jing.system.comm.contants.SystemCons;
import com.jing.system.comm.contants.WeiboCons;
import com.jing.system.comm.enums.FansAttentionType;
import com.jing.weibo.pojo.UserInfo;
import com.jing.weibo.service.user.UserInfoService;
import com.jing.weibo.ws.sina.SinaService;

/**
 * 用户关注和粉丝的Controller
 * @author jing.yue
 * @version 2012/08/29 1.0.0
 */
@Controller
public class FansAttentionController extends BaseController {

	private static final Logger logger = Logger.getLogger(FansAttentionController.class);

	@Autowired
	private SinaService sinaService;

	@Autowired
	private UserInfoService userInfoService;

	/**
	 * 参与互粉
	 * @return
	 */
	@RequestMapping(value = "/fansattention/json/joinMp")
	@ResponseBody
	public ModelMap joinMp(HttpServletRequest request) {
		// TODO Auto-generated method stub
		//logger.info("参与互粉");
		String result = null;
		String weiboMsg = null;
		int addFansNum = 0;
		int addAttentionNum = 0;
		UserInfo userInfo = getSessionUser(request);
		try {
			if(userInfo.getIsopenmp().intValue() == 0) {
				result = ERROR_ISOPENMP;
			}
			else {
				//先同步信息
				//synchrologInfo(request, FansAttentionType.TYPE_ATTENTION, false);
				synchrologInfo(request, FansAttentionType.TYPE_FANS);

				//根据用户名和类型获取参加了互粉的用户和在粉丝中不存在的前100个用户
				userInfo.setJoinmpnum(SystemCons.JOINMP_USERINFO_NUM);
				List<UserInfo> userInfos = userInfoService.findByJoinmpUserInfo(userInfo);
				//User user = null;
				for (UserInfo ui : userInfos) {
					if(addFansNum >= WeiboCons.weibo_mp_max_num) {
						break;
					}
					try {
						//用户关注当前登录用户
						sinaService.createFriendshipsById(userInfo.getUsername(), ui.getToken());
						addFansNum ++;

						try {
							//当前登录用户关注用户
							sinaService.createFriendshipsById(ui.getUsername(), userInfo.getToken());
							/*//添加互粉粉丝

							//添加关注
							Fansattention fa = setFansattention(user, userInfo.getUsername(), FansAttentionType.TYPE_ATTENTION.getCode());
							fa.setFollowing("true");
							fa.setFollowme("true");
							fa.setType(FansAttentionType.TYPE_ATTENTION.getCode());
							fansAttentionService.saveFansattention(fa);*/
							addAttentionNum ++;
						} catch (WeiboException e) {
							logger.error("用户[" + userInfo.getNickname() + "]关注[" + ui.getNickname() + "]异常:" + WeiboCons.getErrorMsg(e), e);
							//添加粉丝
						}

					} catch (WeiboException e) {
						logger.error("用户[" + userInfo.getNickname() + "]添加粉丝[" + ui.getNickname() + "]异常:" + WeiboCons.getErrorMsg(e));
						//token过期或access_token 无效
						if(e.getErrorCode() == 21327 || e.getErrorCode() == 21332) {
							//修改token过期时间
							ui.setAccessendtime(Calendar.getInstance().getTime());
							userInfoService.updateUserInfoTokentime(ui);
						}
					}
				}

				setSessionUser(request, userInfo);
				result = SUCCESS;

				//删除数据库中的同步更新记录
				if(addFansNum > 0) {
					updateSynchrologInfo(request, FansAttentionType.TYPE_ATTENTION);
					updateSynchrologInfo(request, FansAttentionType.TYPE_FANS);

					//发送互粉信息到微博
					String weiboContent = SystemCons.getWeiboMpContent(addFansNum);
					sinaService.updateStatus(weiboContent, userInfo.getToken());
				}
			}

		} catch (WeiboException e) {
			logger.error(WeiboCons.getErrorMsg(e), e);
			result = ERROR_WEIBO;
			weiboMsg = WeiboCons.getErrorMsg(e);
		} catch (Exception e) {
			logger.error("参与互粉异常!", e);
			result = ERROR;
		}
		ModelMap modelMap = new ModelMap();
		modelMap.put("result", result);
		modelMap.put("addFansNum", addFansNum);
		modelMap.put("weiboMsg", weiboMsg);
		modelMap.put("joinMpMsg", "您成功添加了" + addFansNum + "个粉丝/成功关注了" + addAttentionNum + "个用户!");
		return modelMap;
	}
}